<template>
  <div v-for="(section, index) in questionnaire.sections" :key="index">
    <h3>{{ section.title }}</h3>
    <div v-for="question in section.questions" :key="question.id" class="question-card" :data-question-id="question.id">
      <p class="question_description"> {{ question.id }}.{{ question.description }}</p>
      <p>{{ question.text }}</p>
      <!-- 题项 -->
      <el-checkbox-group v-model="answers[question.id]" >
        <el-popover 
          popper-class="popoverSty" 
          v-for="(option, idx) in question.options" 
          :key="idx" 
          trigger="click"
          :width="300" 
          placement="bottom" 
          title="选择系统">
          <template #reference>
            <el-checkbox 
             :value="option"
             @change="handleCheckboxChange(question.id,option, system)"
             >
              {{ option }}
            </el-checkbox>
          </template>
          <!-- 系统 -->
          <el-checkbox-group v-model="selectedSystemMap[question.id]">
            <el-checkbox 
              v-for="system in selectedSystemNames" 
              :key="system" 
              :value="system" 
              :disabled="isSystemDisabled(question.id, system, option,idx)" 
              @change="updateSystemSelection(question.id, option, system)">
              <div>{{ system }}</div>
              <!--  :disabled="isSystemDisabled(question.id, system, option)" 
                
              :disabled="indexType.value === 1 ? isSystemDisabled(question.id, system, option) : indexType.value === 2 ? false : ''"  -->
            </el-checkbox>
          </el-checkbox-group>
        </el-popover>
      </el-checkbox-group>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watch, defineEmits,toRaw } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import questionnaire from "@/assets/js/surveyConfig";
import api from "@/assets/js/api.js"; // 导入公用接口文件

export default {
  name: "Questionnaire",
  props: {
    companyId: Array,
    companyName: Array,
    textareaValue: String,
    name: String,
  },
  setup(props) {
    console.log("公司 ID:", props.companyId);
    console.log("已选系统名称:", props.companyName);
    console.log("公司名称:", props.name);
    console.log("备注:", props.textareaValue);

    const selectedSystemNames = ref([]);
    const emit = defineEmits();
    watch(
      () => props.companyName,
      (newVal) => {
        selectedSystemNames.value = newVal || []; // Update selectedSystemNames when companyName changes
        console.log("Updated selectedSystemNames:", selectedSystemNames.value);
      },
      { immediate: true } // Run immediately to catch initial value
    );
    const parames = reactive({
      selectCompany: "",
      selectSystem: [],
      textareaValue: "",
    });
    // 定义数据
    const parames1 = ref({
      selectSystem: [],
      selectedNames: [],
    });

    // 新增变量 isSystemSelected 用于检查是否已选择系统
    const isSystemSelected = ref(false);
    let answers = reactive({});
    let selectedSystemMap = reactive([]); // 追踪每个题目选项的系统选择
    const questionSystemSelections = reactive({}); // 追踪每个题目中已选择的系统

    // 初始化 answers 回显
    const selectSystemDatas = ref([]);
    const dataName = {
      unitName: "国网四川省电力公司天府新区供电公司",
    };
    const fetchDataAnsers = async () => {
      try {
        let data = await api.post("/system/questionnaire/get", dataName);
        console.log("获取数据", data);
        parames.selectCompany = data.unitName;
        parames.selectSystem = data.systemNames;
        selectSystemDatas.value = data.value; // 赋值
        parames1.value.selectSystem = data.systemNames;
        initializeSelectedSystems(data.value);
      } catch (error) {
        console.error("获取数据失败:", error);
      }
    };

    // 初始化已选系统到 selectedSystemMap 回显
    const initializeSelectedSystems = (selectSystemDatas) => {
      console.log(selectSystemDatas);

      if (!selectSystemDatas || Object.keys(selectSystemDatas).length === 0)
        return;

      Object.entries(selectSystemDatas).forEach(([questionId, options]) => {
        answers[questionId] = Object.keys(options);

        Object.entries(options).forEach(([option, systems]) => {
          const key = `${questionId}-${option}`;
          selectedSystemMap[key] = systems || [];
        });
        // });
        // Object.entries(selectSystemDatas).forEach(([questionId, options]) => {
        //   // 初始化问题的选项选择
        //   answers[questionId] = Object.keys(options);

        //   // 初始化每个选项的系统选择
        //   Object.entries(options).forEach(([option, systems]) => {
        //     const key = `${questionId}-${option}`;
        //     selectedSystemMap[key] = systems;
        //   });

        console.log(answers[questionId]);

        // 检查每个勾选的选项是否有系统选中，如果没有则取消勾选
        // answers[questionId].forEach((option) => {
        //   const key = `${questionId}-${option}`;

        //   if (!selectedSystemMap[key] || selectedSystemMap[key].length === 0) {
        //     const index = answers[questionId].indexOf(option);
        //     if (index > -1) answers[questionId].splice(index, 1); // 取消该选项的勾选状态
        //   }
        // });
      });
    };


    const updateSystemSelection = (questionId, option, system) => {
      const key = `${questionId}-${option}`;
      // console.log('key',key);
      console.log('questionId',questionId);
      console.log('option',option);
      console.log('system',system);
      console.log('answers',answers[questionId]);
      console.log('selectedSystemMap',selectedSystemMap[key]);
      if (!selectedSystemMap[key]) selectedSystemMap[key] = [];
      if (!questionSystemSelections[questionId])
        questionSystemSelections[questionId] = [];

      if (selectedSystemMap[key].includes(system)) {
        // 移除系统
        selectedSystemMap[key] = selectedSystemMap[key].filter(
          (item) => item !== system
        );
        questionSystemSelections[questionId] = questionSystemSelections[
          questionId
        ].filter((item) => item !== system);
      } else {
        // 添加系统
        selectedSystemMap[key].push(system);
        questionSystemSelections[questionId].push(system);
      }

      // 检查该选项是否至少有一个系统被选中
      if (selectedSystemMap[key].length > 0) {
        // 如果该选项有系统被选中，确保它在 answers 中被勾选
        if (!answers[questionId].includes(option)) {
          answers[questionId].push(option);
        }
      } else {
        // 如果没有系统被选中，检查其他选项的系统状态
        const otherOptionsSelected = Object.keys(selectedSystemMap).some(
          (k) =>
            k.startsWith(`${questionId}-`) && selectedSystemMap[k].length > 0
        );

        // 仅在没有其他系统选项被勾选的情况下取消该题目的勾选状态
        if (!otherOptionsSelected) {
          const index = answers[questionId].indexOf(option);
          if (index > -1) {
            answers[questionId].splice(index, 1); // 取消该选项的勾选状态
          }
        }
      }
    };

    const getSelectedSystemsForQuestions = () => {
      const questionSystems = {};
      console.log(selectedSystemMap);

      Object.keys(selectedSystemMap).forEach((key) => {
        const [questionId, option] = key.split("-");
        if (option !== "undefined") {
          // 排除键为 undefined 的项
          if (!questionSystems[questionId]) questionSystems[questionId] = {};
          // 仅当数组不为空时添加
          if (selectedSystemMap[key] && selectedSystemMap[key].length > 0) {
            questionSystems[questionId][option] = selectedSystemMap[key];
          }
        }
      });

      // 移除键为 'undefined' 的值
      Object.keys(questionSystems).forEach((key) => {
        if (questionSystems[key].hasOwnProperty("undefined")) {
          delete questionSystems[key]["undefined"];
        }
      });

      return questionSystems;
    };
    const getKeysAndValues = (proxyObject) => {
      const rawObject = toRaw(proxyObject); // 获取原始对象
      const result = []; // 用于存储键值对的数组

      for (const key in rawObject) {
        if (rawObject.hasOwnProperty(key)) {
          result.push({ key, value: rawObject[key] }); // 将键值对存入数组
        }
      }

      return result;
    };

    let questionSyst = reactive({});
    const handleboxChange = (value) => {
      questionSyst = value;
      console.log("questionSyst", questionSyst);
    }

    let indexType = ref(1);
    const handleCheckboxChange = (questionId,opti,system) => {
      
      const selectedAnswers = answers[questionId] || []; // 获取当前问题的已选择答案
      const key = `${questionId}-${opti}`;

      console.log('questionId',key);
      console.log('questionId',questionId);
      console.log('option',opti);
      console.log('system',system);
      console.log('answers',answers[questionId]);
      console.log('selectedSystemMap',selectedSystemMap[key]);

      // 系统有勾选数据 ，不让题取消勾选
      if(selectedSystemMap[key] !==0){
        answers[questionId].push(opti);
      }
      
      
      // if (selectedSystemMap[key] === undefined || selectedSystemMap[key] === 0) {
      //   console.log(2222);
        
      //   answers[questionId] = answers[questionId].pop()
      // }
      // 检查每个勾选的选项是否有系统选中，如果没有则取消勾选
      selectedAnswers.forEach((option) => {
        const key = `${questionId}-${option}`;
        console.log(answers[key]);
        
        console.log(answers[questionId]);
        // console.log(JSON.parse(JSON.stringify(selectedAnswers)));
        // 初始化 selectedSystemMap[key] 为数组
        if (!selectedSystemMap[key]) selectedSystemMap[key] = []
        // console.log("Checking key:", key, "selectedSystemMap:", selectedSystemMap);

        if (selectedSystemMap[key].length === 0) {
          // answers[questionId] = []
          // return
          // 取消该选项的勾选状态
          const index = answers[questionId].indexOf(option);
          if (index > -1) answers[questionId].splice(index, 1);

          // 清除该选项下的系统，但保留空数组
          selectedSystemMap[key] = [];
        } else {
          // answers[questionId].push(opti); // 如果有选中的系统，确保该选项保持勾选状态
          
          // 系统存在，确保选项在数组中
          const index = answers[questionId].indexOf(option);
          if (index === -1) {
            answers[questionId].push(option); // 添加选项以确保勾选状态
          }
        }
      });

    };


    
    // 判断某系统选项是否已被当前题目其他选项选择，只有在同一题目的其他题项中该系统被选择时才禁用
    let isSystemDisabled = (questionId, system, option,index) => { 
      // questionSystemSelections[questionId]?.includes(system) && !selectedSystemMap[`${questionId}-${option}`]?.includes(system) ) ;
      const key = `${questionId}-${system}`;
      // console.log("Checking key:", key, "option:", option);
      // console.log("system:", system);
      // console.log("questionSystemSelections:", questionSystemSelections);
      // console.log("题项里已经勾选的系统selectedSystemMap:", selectedSystemMap[`${questionId}-${option}`]);
      // console.log("题项", answers[questionId]);
      // console.log("一点击的题项下标", index);
      


      // selectedSystemMap[`${questionId}-${option}`] = [];

  // const key = `${questionId}-${option}`;
  //     // 如果当前选项的系统选择为空数组，返回 false（非禁用状态）
  // if (selectedSystemMap[key]?.length === 0) {
  //   return false;
  // }

  // // 检查当前选项是否包含该系统
  // const isCurrentlySelected = selectedSystemMap[key]?.includes(system);

  // // 检查同一题目的其他选项是否包含该系统
  // const isOtherOptionSelected = questionSystemSelections[questionId]?.some(
  //   (selectedSystem) => selectedSystem === system && !isCurrentlySelected
  // );

  // console.log(isOtherOptionSelected);
  // // 如果系统被其他选项选中则禁用；否则启用（非禁用）
  // return isOtherOptionSelected;
  


    //  // 判断当前选项是否包含该系统
    //     const isCurrentlySelected = selectedSystemMap[`${questionId}-${option}`]?.includes(system);

    //   // 检查同一题目其他选项是否包含该系统
    //   const isOtherOptionSelected = questionSystemSelections[questionId]?.some(
    //     (selectedSystem) => selectedSystem === system && !isCurrentlySelected
    //   );
    //   console.log(isOtherOptionSelected);
      
    //   // 如果系统被其他选项选中则禁用；如果当前选项被取消勾选则启用（非禁用）
    //   return isOtherOptionSelected;
      return (
        questionSystemSelections[questionId]?.includes(system) && !selectedSystemMap[`${questionId}-${option}`]?.includes(system) ) ;
    };


    // 滚动到指定元素
    const scrollToElement = (selector) => {
      const element = document.querySelector(selector);
      if (element) {
        element.scrollIntoView({ behavior: "smooth" });
      }
    };
    const submitAnswers = async () => {
      console.log(selectedSystemMap);
      
      // 检查每个问题是否已被回答。
      const allQuestionsAnswered = questionnaire.sections.every((section) =>
        section.questions.every((question) => {
          // 对于复选框问题，确保 answers[question.id] 存在并且有值。
          if (question.type === "checkbox") {
            return answers[question.id] && answers[question.id].length > 0;
          }
          return (
            answers[question.id] !== undefined && answers[question.id] !== ""
          );
        })
      );
      if (!allQuestionsAnswered) {
        const unansweredQuestions = questionnaire.sections.flatMap((section) =>
          // section.questions.filter(question => !answers[question.id])
          section.questions.filter(
            (question) =>
              !answers[question.id] || answers[question.id].length === 0
          )
        );
        const firstUnansweredQuestion = unansweredQuestions[0];

        if (firstUnansweredQuestion) {
          scrollToElement(
            `.question-card[data-question-id="${firstUnansweredQuestion.id}"]`
          ); // 滚动到未回答的问题
        }
        ElMessage.warning("请确保每道题都已作答！");
        return;
      }


      // 检查每个问题是否选择了题但未选择系统
      const incompleteSystemSelections = questionnaire.sections.flatMap((section) =>
        section.questions.filter((question) => {
          // 检查答案存在但 selectedSystemMap 中没有对应系统选择
          return (
            answers[question.id] &&
            !Object.keys(selectedSystemMap).some((key) =>
              key.startsWith(`${question.id}-`)
            )
          );
        })
      );
      if (incompleteSystemSelections.length > 0) {
        const firstIncompleteSystemSelection = incompleteSystemSelections[0];
        scrollToElement(
          `.question-card[data-question-id="${firstIncompleteSystemSelection.id}"]`
        ); // 滚动到未选择系统的题目
        ElMessage.warning("请为每道题目选择至少一个系统！");
        return;
      }

      // 检查每个选定的系统是否已对每个问题进行评估
      let missingEvaluations = [];
      questionnaire.sections.forEach((section) => {
        section.questions.forEach((question) => {
          console.log(selectedSystemNames.value);

          // 遍历选定的系统，并检查每个问题的系统是否有对应的评价
          selectedSystemNames.value.forEach((system) => {
            const systemEvaluated = Object.keys(selectedSystemMap).some(
              (key) =>
                key.startsWith(`${question.id}-`) &&
                selectedSystemMap[key].includes(system)
            );
            console.log(systemEvaluated);

            if (!systemEvaluated) {
              missingEvaluations.push(
                `题目${question.id} 缺少系统【${system}】的评价`
              );
            }
          });
        });
      });
      // 处理缺少的系统评估项
      if (missingEvaluations.length > 0) {
        const firstUnansweredQuestion = document.querySelector(
          `.question-card[data-question-id="${
            missingEvaluations[0].match(/\d+/)[0]
          }"]`
        );
        if (firstUnansweredQuestion) {
          firstUnansweredQuestion.scrollIntoView({ behavior: "smooth" });
        }
        // 显示错误提示框
        ElMessageBox.alert(
          `<span style='color: red'>提交失败！</span>以下项缺少系统评价:<br>${missingEvaluations.join(
            "<br>"
          )}`,
          "错误提示",
          {
            dangerouslyUseHTMLString: true,
            confirmButtonText: "确定",
          }
        );
        return;
      } else {
        console.log("没有缺少的评价。");
      }

      console.log(answers);
      let answer = ref({});
      // let answer = getSelectedSystemsForQuestions()
      answer = getSelectedSystemsForQuestions();
      console.log(answer);
      const payload = {
        value: answer,
        unitName: props.name,
        systemNames: props.companyName,
        systemIds: props.companyId,
        remarks: props.textareaValue,
      };
      // const payload = {
      //   value: answer,
      //   // unitName: props.name,
      //   unitName: '国网四川省电力公司天府新区供电公司',
      //   systemNames: ["营销智慧引擎", "用电信息采集系统"],
      //   systemIds:[3,4],
      //   remarks: props.textareaValue,
      // };

      console.log(payload);
      // return;
      try {
        const response = await api.post("/system/questionnaire/add", payload);
        if (response.code == 200) {
          ElMessage.success("感谢您的反馈！");
          resetForm();
        } else {
          ElMessage.error("提交失败，请重试！");
        }
      } catch (error) {
        ElMessage.error("提交数据失败:", error);
      }
    };

    // 重置数据
    const resetForm = () => {
      parames.selectCompany = "";
      parames.selectSystem = [];
      parames.textareaValue = "";
      parames1.value.selectSystem = [];
      parames1.value.selectedNames = [];
      Object.keys(answers).forEach((key) => delete answers[key]);
      Object.keys(selectedSystemMap).forEach(
        (key) => delete selectedSystemMap[key]
      );
      Object.keys(questionSystemSelections).forEach(
        (key) => delete questionSystemSelections[key]
      );
    };

    const clearParent = () => {
      emit("clear"); // 触发清空事件
    };
    const handleDirectSelect = (questionId, option) => {
      answers[questionId] = [option];
    };

    // 组件挂载后获取数据
    onMounted(() => {});

    return {
      questionnaire,
      answers,
      submitAnswers,
      parames,
      selectedSystemMap,
      questionSystemSelections,
      isSystemDisabled,
      updateSystemSelection,
      handleCheckboxChange,
      getSelectedSystemsForQuestions,
      handleDirectSelect,
      selectedSystemNames,
      clearParent,
      handleboxChange,
      indexType
    };
  },
};
</script>

<style scoped>
.question-card {
  margin-bottom: 20px;
}

.el-checkbox-group {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.el-radio-group {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.el-header {
  margin-bottom: 40px;
}

.el-header,
.el-footer {
  text-align: center;
}

.question_description {
  font-weight: bold;
}

.selectsty {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;

  .elselect {
    width: 48%;
    display: flex;
    flex-direction: row;
    align-items: center;
  }

  .elselect span {
    display: inline-block;
    width: 65px;
  }
}

.highlighted {
  background-color: #cce8ff;
  /* 高亮的背景色，可以根据需求调整 */
  color: #0066cc;
  font-weight: bold;
}

.fixed-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  z-index: 1000;
  box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.1);
  padding: 10px 20px;
}

.el-main {
  padding-bottom: 60px;
  /* 根据 footer 的高度调整 */
}
</style>
